﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Model.Config;
using System.Text;

namespace TemplateApiCore
{
    public static class JwtExtension
    {
        public static void AddJwtExtension(this WebApplicationBuilder builder)
        {
            //NuGet package: Microsoft.AspNetCore.Authentication.JwtBearer
            //注册JWT配置文件
            builder.Services.Configure<JWTTokenOptions>(builder.Configuration.GetSection("JWTTokenOptions"));
            //添加jwt验证（适用于[Authorize] 接口）（jwt官网：https://jwt.io/）
            JWTTokenOptions tokenOptions = new JWTTokenOptions();
            builder.Configuration.Bind("JWTTokenOptions", tokenOptions);//配置文件绑定
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options => //这里是配置的鉴权的逻辑
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        //JWT有一些默认的属性，就是给鉴权时就可以筛选了
                        ValidateIssuer = true,//是否验证Issuer发布者
                        ValidateAudience = true,//是否验证Audience接收者
                        ValidateLifetime = true,//是否验证Token的过期时间
                        ValidateIssuerSigningKey = true,//是否验证发布者密钥
                        ValidIssuer = tokenOptions.Issuer,//发布者
                        ValidAudience = tokenOptions.Audience,//接收者这两项和前面签发jwt的设置一致
                        ClockSkew = TimeSpan.FromSeconds(0),//设置token过期后多久失效，默认过期后300秒内仍有效                        
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecuritKey))//密钥
                    };
                });
        }
    }
}
